import { DeleteOutlined, EditOutlined, ExportOutlined, EyeOutlined, PieChartOutlined, PlayCircleOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Badge, Button, Form, Popconfirm, message } from 'antd';
import React, { useRef, useState } from 'react';
import { batchDelCase, countCase, execute, getReportApiPage } from './service';
import { history, useModel, useRequest, useSearchParams } from '@umijs/max';
import CustomCode from '@/components/CustomCode';
import { getStressCasePage } from '@/pages/stress-test/case/service';
import { getApiCasePage } from '@/pages/api-auto/case/service';
import { exportExcel } from '../stress-test/service';

const handleRemove = async (idList: any[], projectId: any) => {
  const hide = message.loading('正在删除');
  if (!idList) return true;

  try {
    const res = await batchDelCase({
      idList,
      projectId,
      type: 'API'
    });
    hide();
    if (res.code == 0) {
      message.success('删除成功，即将刷新');
      return true;
    }
    return false
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams()
  const caseId = searchParams.get("caseId")
  const [form] = Form.useForm()
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const { initialState } = useModel('@@initialState');

  const columns: ProColumns<any>[] = [
    {
      title: '报告名称',
      dataIndex: 'name',
      fixed: 'left',
      ellipsis: true,
      render(dom, entity, index, action, schema) {
        return <div>{dom}</div>
      },
    },
    {
      title: '报告类型',
      dataIndex: 'type',
      valueType: 'select',
      hideInSearch: true,
      valueEnum: {
        STRESS: { text: '压测' },
        API: { text: '接口' },
        UI: { text: 'UI自动化' },
      }
    },
    {
      title: '用例',
      dataIndex: 'caseId',
      valueType: 'select',
      async request() {
        const res = await getApiCasePage({
          current: 1,
          pageSize: 1000,
          projectId: initialState?.currentProject?.id,
        })
        const data = res?.data?.currentData || []
        return data?.map((item: any) => ({
          label: item.name,
          value: item.id
        }))
      },
    },

    {
      title: '执行状态',
      dataIndex: 'executeState',
      valueType: 'select',
      valueEnum: {
        EXECUTE_SUCCESS: { text: '执行成功', status: 'success' },
        EXECUTING: { text: '执行中', status: 'Processing' },
        COUNTING_REPORT: { text: '统计报告', status: 'Processing' },
        EXECUTE_FAIL: { text: '执行失败', status: 'error' },
      }
    },
    {
      title: '总量',
      dataIndex: 'quantity',
      hideInSearch: true,
    },
    {
      title: '失败数量',
      dataIndex: 'failQuantity',
      hideInSearch: true,
    },
    {
      title: '摘要',
      dataIndex: 'summary',
      hideInSearch: true,
      render(dom, entity, index, action, schema) {
        return <CustomCode width={340} height={120} value={dom} />
      },
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '修改时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record: any) => [
        <a
          key="config"
          onClick={() => {
            history.push('/report/api-test-detail?reportId=' + record?.id)
          }}
        >
          <EyeOutlined /> 详情
        </a>,
        <Popconfirm key='del' title={`是否要删除此用例？`} onConfirm={async () => {
          const res = await handleRemove([record?.id], initialState?.currentProject?.id);
          if (res) {
            actionRef.current?.reload()
            setSelectedRows([]);
          }
        }}>
          <a><DeleteOutlined /> 删除</a>
        </Popconfirm>
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any>
        actionRef={actionRef}
        rowKey="id"
        search={{
          form
        }}
        scroll={{ x: 'max-content' }}
        toolbar={{
          actions: [
            <Button
              key="export"
              icon={<ExportOutlined />}
              onClick={() => {
                exportExcel({
                  ...form.getFieldsValue(),
                  projectId: initialState?.currentProject?.id,
                  type: 'API',
                })
              }}
            >
              导出
            </Button>,
          ],
        }}
        onSubmit={() => {
          if (form.getFieldValue('caseId')) {
            setSearchParams({ caseId: form.getFieldValue('caseId') })
          } else if (caseId) {
            form.setFieldsValue({ caseId })
          }
        }}
        onReset={() => {
          setSearchParams({})
          form.resetFields(['caseId'])
        }}
        request={async ({ pageSize, current, ...params }) => {
          if (!form.getFieldValue('caseId') && caseId) {
            form.setFieldsValue({
              caseId: +caseId
            })
          }
          const res = await getReportApiPage({
            current,
            pageSize,
            ...params,
            caseId,
            projectId: initialState?.currentProject?.id,
            type: 'API'
          })
          const total = res?.data?.totalRecords || 0
          const data = res?.data?.currentData || []
          return {
            data,
            total,
          }
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys: selectedRowsState?.map((item: any) => item.id),
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              {/* <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span> */}
            </div>
          }
        >
          <Popconfirm key='del' title={`是否要批量删除 ${selectedRowsState.length} 条？`} onConfirm={async () => {
            const res = await handleRemove(selectedRowsState?.map((item: any) => item.id), initialState?.currentProject?.id);
            if (res) {
              actionRef.current?.reload()
              setSelectedRows([]);
            }
          }}>
            <Button danger>
              批量删除
            </Button>
          </Popconfirm>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
